package com.wing.cabinet.controller.app;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.cabinet.model.entity.CellInventoryInout;
import com.wing.cabinet.model.entity.CellInventoryInoutDetail;
import com.wing.cabinet.model.entity.UseInventoryInout;
import com.wing.cabinet.model.request.CellInventoryInoutDetailForm;
import com.wing.cabinet.model.request.CellInventoryInoutForm;
import com.wing.cabinet.model.response.CellInventoryInoutDetailVO;
import com.wing.cabinet.service.CellInventoryInoutDetailService;
import com.wing.common.constant.CabAuthCode;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.web.utils.JwtUtils;
import com.wing.web.utils.LocaleMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 *
 * @author
 */
@Validated
@Api(value = "App-领新明细管理", tags = "售刀柜上货/领取明细管理")
@RestController("appCellInventoryInoutDetailController")
@RequestMapping("cabinet/app/cellInventoryInoutDetail")
@Slf4j
public class CellInventoryInoutDetailController {

    @Autowired
    private CellInventoryInoutDetailService cellInventoryInoutDetailService;
    @Autowired
    private LocaleMessage localeMessage;

    @ApiOperation(value = "领新明细", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "inoutId", value="领新订单ID", defaultValue = "", example = "", dataType = "Long", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<CellInventoryInoutDetailVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,Long inoutId
            ,Long id
            ,String skuCode
    ){

        Page<CellInventoryInoutDetail> pg = new Page<>(page, limit);
        Map queryParam=new HashMap();
        queryParam.put("sort", StrUtil.toUnderlineCase(sort));
        queryParam.put("order",order);
        queryParam.put("inoutId",inoutId);
        queryParam.put("id",id);
        queryParam.put("skuCode",skuCode);
        //搜索

        IPage<CellInventoryInoutDetailVO> list = cellInventoryInoutDetailService.pageList4app(pg,queryParam);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @GetMapping("/{id}")
    public JsonResult detail(@PathVariable("id") Long cellInventoryInoutDetailId) {
        CellInventoryInoutDetailVO cellInventoryInoutDetailVO = cellInventoryInoutDetailService.get4appById(cellInventoryInoutDetailId);
        if (cellInventoryInoutDetailVO == null) {
            return JsonResult.fail(localeMessage.getMessage("common.fail"));
        }
        return JsonResult.success(localeMessage.getMessage("common.success"), cellInventoryInoutDetailVO);
    }

    @PostMapping()
    public JsonResult add(@Validated CellInventoryInoutDetailForm cellInventoryInoutDetailForm) {
        if (cellInventoryInoutDetailService.add(cellInventoryInoutDetailForm) > 0) {
            return JsonResult.success(localeMessage.getMessage("common.success"));
        }
        return JsonResult.fail(localeMessage.getMessage("common.fail"));
    }

    @ApiOperation(value = "售刀柜领取", notes = "领取")
    @PostMapping("/inventoryOut")
    public JsonResult inventoryOut(@RequestBody CellInventoryInoutForm cellInventoryInoutForm){
        try{
            String cabAuthCodes= JwtUtils.getCabAuthCodes();
            if (!cabAuthCodes.contains(CabAuthCode.RECEIVE_KNIFE_AUTH_CODE)){
                return JsonResult.fail("此用户无领新权限,请配置此用户角色的领新权限");
            }
            log.info("inventory out param:{}", JSON.toJSONString(cellInventoryInoutForm));
            cellInventoryInoutForm.getDetailList().get(0).setWorkOrderId(cellInventoryInoutForm.getWorkOrderId());
            cellInventoryInoutForm.getDetailList().get(0).setProcessId(cellInventoryInoutForm.getProcessId());
            String uuid = UUID.randomUUID().toString();
            cellInventoryInoutForm.setUuid(uuid);
            CellInventoryInout cellInventoryInout=cellInventoryInoutDetailService.inventoryOut(cellInventoryInoutForm.getDetailList(),cellInventoryInoutForm.getDeviceCode(),CellInventoryInout.BusinessType.cellCabOut, UseInventoryInout.BusinessType.cellCabOut,cellInventoryInoutForm.getByPassword(),cellInventoryInoutForm.getStoresRequisitionId(), uuid);
            return JsonResult.success(cellInventoryInout);
        }catch (Exception e){
            log.error("cell inventory out fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "邮件发送测试接口")
    @GetMapping("/sendTest/{mailTo}")
    public JsonResult<String> sendTest(@PathVariable("mailTo")String mailTo){
        return cellInventoryInoutDetailService.sendTest(mailTo);
    }

    @ApiOperation(value = "售刀柜清空", notes = "领取")
    @PostMapping("/empty/inventoryOut")
    public JsonResult inventoryOutEmpty(@RequestBody CellInventoryInoutForm cellInventoryInoutForm){
        try{
//            String cabAuthCodes= JwtUtils.getCabAuthCodes();
//            if (!cabAuthCodes.contains(CabAuthCode.RECEIVE_KNIFE_AUTH_CODE)){
//                return JsonResult.fail("此用户无领新权限,请配置此用户角色的领新权限");
//            }
            log.info("inventory out empty param:{}", JSON.toJSONString(cellInventoryInoutForm));
            cellInventoryInoutForm.getDetailList().get(0).setWorkOrderId(cellInventoryInoutForm.getWorkOrderId());
            cellInventoryInoutForm.getDetailList().get(0).setProcessId(cellInventoryInoutForm.getProcessId());
            cellInventoryInoutDetailService.inventoryOutEmpty(cellInventoryInoutForm.getDetailList(),cellInventoryInoutForm.getDeviceCode(),CellInventoryInout.BusinessType.cellCabOut, UseInventoryInout.BusinessType.cellCabOut);
            return JsonResult.success();
        }catch (Exception e){
            log.error("cell inventory out fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "售刀柜领取", notes = "领取")
    @PostMapping("/inventoryOutByPassword")
    public JsonResult inventoryOutByPassword(@RequestBody CellInventoryInoutForm cellInventoryInoutForm){
        try{
            log.info("inventory out param:{}", JSON.toJSONString(cellInventoryInoutForm));
            cellInventoryInoutForm.getDetailList().get(0).setWorkOrderId(cellInventoryInoutForm.getWorkOrderId());
//            CellInventoryInout cellInventoryInout=cellInventoryInoutDetailService.inventoryOut(cellInventoryInoutForm.getDetailList(),cellInventoryInoutForm.getDeviceCode(),CellInventoryInout.BusinessType.cellCabOut, UseInventoryInout.BusinessType.cellCabOut,true,cellInventoryInoutForm.getStoresRequisitionId());
            cellInventoryInoutForm.setUuid(UUID.randomUUID().toString());
            CellInventoryInout cellInventoryInout=cellInventoryInoutDetailService.inventoryOut(cellInventoryInoutForm);
            return JsonResult.success(cellInventoryInout);
        }catch (Exception e){
            log.error("cell inventory out fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "售刀柜上货", notes = "上货")
    @PostMapping("/inventoryIn")
    public JsonResult inventoryIn(@RequestBody CellInventoryInoutForm cellInventoryInoutForm){
        try{
            cellInventoryInoutForm.setBusinessType(CellInventoryInout.BusinessType.inByLoad);
            cellInventoryInoutDetailService.inventoryIn(cellInventoryInoutForm);
            return JsonResult.success();
        }catch (Exception e){
            log.error("cell inventory out fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "售刀柜上货", notes = "上货")
    @PostMapping("/inventoryInInit")
    public JsonResult inventoryInInit(@RequestBody List<CellInventoryInoutForm> cellInventoryInoutForm){
        try{
            cellInventoryInoutDetailService.inventoryIn(cellInventoryInoutForm);
            return JsonResult.success();
        }catch (Exception e){
            log.error("cell inventory out fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "售刀柜上货货道是否够存", notes = "上货")
    @PostMapping("/isInventoryIn")
    public JsonResult isInventoryIn(@RequestBody CellInventoryInoutDetailForm cellInventoryInoutDetailForm){
        return cellInventoryInoutDetailService.isInventoryIn(cellInventoryInoutDetailForm);
    }

    @ApiOperation(value = "售刀柜领取是否有权限", notes = "领取")
    @PostMapping("/verifyPermissions")
    public JsonResult verifyPermissions(@RequestBody CellInventoryInoutForm cellInventoryInoutForm){
//        try{
//            return JsonResult.success(cellInventoryInoutDetailService.verifyPermissions(cellInventoryInoutForm.getDetailList()));
//        }catch (Exception e){
//            log.error("verifyPermissions fail",e);
//        }
        //log.info("verify permission param:{}",JSON.toJSONString(cellInventoryInoutForm));
        //return cellInventoryInoutDetailService.verifyPermissions(cellInventoryInoutForm.getDetailList());

        try{
            log.info("verify permission param:{}",JSON.toJSONString(cellInventoryInoutForm));
            //return cellInventoryInoutDetailService.verifyPermissions(cellInventoryInoutForm.getDetailList());
            return cellInventoryInoutDetailService.verifyPermissionsNew(cellInventoryInoutForm.getDetailList());
        }catch (Exception e){
            log.error("verify permission fail",e);
            return JsonResult.fail("权限判定异常",e.getMessage());
        }
    }

}
